package com.joyintech.config;


import com.joyintech.util.ResponseData;
import com.joyintech.util.ZhfxCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局的的异常拦截器（拦截所有的控制器）
 *
 * @author fengshuonan
 * @date 2016年11月12日 下午3:19:56
 */
@RestControllerAdvice
@Order(-1)
public class McpExceptionHandler implements ResponseBodyAdvice<Object> {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private static final String ERROR_MESSAGE_PREFIX = "Error:";

    @ResponseBody
    @ExceptionHandler(McpException.class)
    public ResponseData customException(McpException ex){
        log.error("customException",ex);
        ResponseData responseData = new ResponseData(ZhfxCode.ZHFX_000099);
        responseData.setResponseMessage(ex.getMessage());
        return responseData;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseData handleException(Exception e) {
        log.error("handleException",e);
        ResponseData responseData = new ResponseData(ZhfxCode.ZHFX_000099);
        responseData.setResponseMessage(e.getMessage());
        return responseData;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        log.info("beforeBodyWrite {}",returnType.getGenericParameterType().getTypeName());
        if(returnType.getGenericParameterType().equals(ResponseData.class)){
            ResponseData appReply = (ResponseData) o;
            return appReply;
        }
        return o;
    }
}
